//
//  YMNetwork.m
//  GuoAo
//
//  Created by y s on 2023/3/9.
//

#import "YMNetwork.h"
#import <AFNetworking/AFNetworking.h>

#define kNetwork_OutTime 15

@interface YMNetwork ()

@property (strong, nonatomic) AFHTTPSessionManager *mananger;

@end

@implementation YMNetwork


+ (instancetype)shared{
    static dispatch_once_t onceToken;
    static YMNetwork *sharedInstance;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[YMNetwork alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init{
    self = [super init];
    if (self){
        self.mananger = [AFHTTPSessionManager manager];
        self.mananger.requestSerializer = [AFHTTPRequestSerializer serializer];
        self.mananger.requestSerializer = [AFJSONRequestSerializer serializer];
        self.mananger.requestSerializer.timeoutInterval = kNetwork_OutTime;
        //此处应该添加一些服务器指定的的请求头信息
        [self.mananger.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        // 返回JSON格式
        self.mananger.responseSerializer = [AFJSONResponseSerializer serializer];
        self.mananger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        self.mananger.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", nil];
        
    }
    return self;
}


//GET请求
+ (void)getWithUrl:(NSString *)url
        parameters:(NSDictionary *)parameters
           success:(YSSuccessBlock)success
           failure:(YSFailureBlock)failure {
    
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];
    
    NSURLSessionDataTask *task = [mananger GET:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            //请求成功
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    [task resume];
}

//Post请求
+ (void)postWithUrl:(NSString *)url
         parameters:(id)parameters
            success:(YSSuccessBlock)success
            failure:(YSFailureBlock)failure {
    
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];
    NSURLSessionDataTask *task = [mananger POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            //请求成功
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    [task resume];
}

//PUT请求
+ (void)putWithUrl:(NSString *)url
        parameters:(NSDictionary *)parameters
           success:(YSSuccessBlock)success
           failure:(YSFailureBlock)failure {
    
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];
    NSURLSessionDataTask *task = [mananger PUT:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            //请求成功
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    [task resume];
}
//Delete请求
+ (void)deleteWithUrl:(NSString *)url
           parameters:(NSDictionary *)parameters
              success:(YSSuccessBlock)success
              failure:(YSFailureBlock)failure {
    
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];

    NSURLSessionDataTask *task = [mananger DELETE:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            //请求成功
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    [task resume];
}

//上传文件
+ (void)uploadWithUrl:(NSString *)url
             filePath:(NSString *)filePath
             fileName:(NSString *)fileName
                 name:(NSString *)name
             mimeType:(NSString *)mimeType
           parameters:(NSDictionary *)parameters
              success:(YSSuccessBlock)success
              failure:(YSFailureBlock)failure
{
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];
    
    NSURLSessionDataTask *task = [mananger POST:url parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name fileName:fileName mimeType:mimeType error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        if (success){
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    [task resume];
}
//上传data 文件
+ (void)uploadDataWithUrl:(NSString *)url
                 fileData:(NSData *)fileData
                 fileName:(NSString *)fileName
                     name:(NSString *)name
                 mimeType:(NSString *)mimeType
               parameters:(NSDictionary *)parameters
                  success:(YSSuccessBlock)success
                  failure:(YSFailureBlock)failure {
    
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];
    
    NSURLSessionDataTask *task = [mananger POST:url parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:mimeType];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        if (success){
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    [task resume];
}



//下载文件
+ (void)downloadWithUrl:(NSString *)url
                success:(void(^)(NSURL *path))success
                failure:(YSFailureBlock)failure {
    
    AFHTTPSessionManager *mananger = [YMNetwork getSessionManager:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    NSURLSessionDownloadTask *downloadTask = [mananger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        /* 设定下载到的位置 */
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename]; //文件位置
        return url;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成之后的操作
        if (error != nil){
            if (failure){
                failure(error);
            }
        }else{
            if (success){
                success(filePath);
            }
        }
        
    }];
    [downloadTask resume];
}

+ (AFHTTPSessionManager *)getSessionManager:(NSString *)url{
    AFHTTPSessionManager *manager = [YMNetwork shared].mananger;
    if ([url hasPrefix:KTuoToUrl]){
        NSString *tuoTuToken = [SDataUtil stringOf:[YMMyModel shared].tuoTuToken valid:[YMMyModel shared].noLoginTuoTuToken];
        if (tuoTuToken != nil && tuoTuToken.length > 0){
            [manager.requestSerializer setValue:tuoTuToken forHTTPHeaderField:@"Authorization"];
        }
    }else{
        if ([YMMyModel shared].token != nil && [YMMyModel shared].token.length > 0){
            [manager.requestSerializer setValue:[YMMyModel shared].token forHTTPHeaderField:@"Authorization"];
            NSString *languageStr = @"zh_CN";
            if([YMLanguageUtil isEnglish]){
                languageStr = @"en_US";
            }
            [manager.requestSerializer setValue:languageStr forHTTPHeaderField:@"Accept-Language"];
        }
    }
    
    return manager;
}

+ (NSString *)jsonStringOfDictionary:(NSDictionary *)dict {
    if (![dict isKindOfClass:[NSDictionary class]] ||
        ![NSJSONSerialization isValidJSONObject:dict]) {
        return @"";
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;

}

+ (BOOL)tuoTuSuccess:(NSString *)status{
    if (status != nil && [status isEqualToString:@"success"]){
        return YES;
    }
    return NO;
}

@end
